/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcDetailPresenter.java
 *   @Date: 19-1-15 下午6:45
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.presenter;

import android.text.TextUtils;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.utils.IntentUtils;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.otc.OtcApi;
import io.bhex.sdk.otc.OtcOrderApi;
import io.bhex.sdk.otc.OtcUserApi;
import io.bhex.sdk.otc.bean.OrderCreateResponse;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcCreateOrderRequestBean;
import io.bhex.sdk.otc.bean.OtcItemSimpleResponse;
import io.bhex.sdk.otc.bean.OtcListResponse;
import io.bhex.sdk.otc.bean.OtcUserInfo;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.TradeApi;
import io.bhex.sdk.trade.bean.AssetDataResponse;
import io.bhex.sdk.trade.bean.AssetListResponse;

public class OtcDetailPresenter extends BasePresenter<OtcDetailPresenter.OtcDetailUI> {

    public interface OtcDetailUI extends AppUI{
        void showOtcDetail(OtcItemSimpleResponse response);

        void needRefreshOtcDetail();

        void showOtcUserInfo(OtcUserInfo response);

        void updateAssettByToken(OtcListResponse.OtcItemBean itemBean, String free);

        void showIsShowRiskTips(boolean isShowRiskTips);
    }


    @Override
    public void onUIReady(BaseCoreActivity activity, OtcDetailUI ui) {
        super.onUIReady(activity, ui);
        getOtcUserInfo();
        getOtcConfig();
    }

    public void getOtcConfig() {
        OtcApi.getConfig(new SimpleResponseListener<OtcConfigResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcConfigResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showIsShowRiskTips(response.getIsShare()==1);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    private void getOtcUserInfo() {
        OtcUserApi.getOtcUserInfo(new SimpleResponseListener<OtcUserInfo>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcUserInfo response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    getUI().showOtcUserInfo(response);
                }

            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取Otc详情
     * @param item
     */
    public void getOtcDetail(OtcListResponse.OtcItemBean item) {
        OtcApi.getOtcDetailSimple(item.getId(),new SimpleResponseListener<OtcItemSimpleResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcItemSimpleResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showOtcDetail(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });

    }

    /**
     * 下单
     * @param isBuy
     * @param otcCreateOrderRequestBean
     */
    public void createOtcOrder(final boolean isBuy, OtcCreateOrderRequestBean otcCreateOrderRequestBean) {
        OtcOrderApi.orderCreate(otcCreateOrderRequestBean,new SimpleResponseListener<OrderCreateResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OrderCreateResponse response) {
                super.onSuccess(response);
                getUI().needRefreshOtcDetail();
                if (CodeUtils.isSuccess(response,true)) {
                    //                    ToastUtils.showShort(getString(R.string.string_create_order_success));
                    if (response.isSuccess()) {
                        String orderId = response.getOrderId();
                        IntentUtils.goOtcBuySellPay(getActivity(),isBuy,orderId);
                        getActivity().finish();
                    }else{
                        ToastUtils.showShort(getActivity(),getString(R.string.string_create_order_failed));
                    }
                }
//                else{
//                    if (response.getCode().equals("42004")) {
//                        //在交易前你需要设置昵称和资金密码
//                        IntentUtils.goSetOtcNickName(getActivity());
//                    }else if(response.getCode().equals("42000")){
//                        //TODO 实名认证
//                    }
//                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取资产
     * @param itemBean
     */
    public void getAvaliableAsset(OtcListResponse.OtcItemBean itemBean) {
        getAssetList(itemBean);
        getAsset(itemBean);
    }

    /**
     * 获取资产列表
     * @param otcItemBean
     */
    protected synchronized void getAssetList(final OtcListResponse.OtcItemBean otcItemBean){
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        TradeApi.SubTokenBalanceChange(otcItemBean.getTokenId(),new SimpleResponseListener<AssetListResponse.BalanceBean>() {

            @Override
            public void onSuccess(AssetListResponse.BalanceBean response) {
                super.onSuccess(response);
                if (getUI() == null || !getUI() .isAlive() || response == null)
                    return;
                if (response != null) {
                    getUI().updateAssettByToken(otcItemBean,response.getFree());
                }else{
                    //因为API接口返回的资产列表，如果没有资产，则没有改币种资产信息，所以为空，代表没有查询到余额 默认按零资产处理
                    getUI().updateAssettByToken(otcItemBean,"0");
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取资产
     * @param itemBean
     */
    protected void getAsset(final OtcListResponse.OtcItemBean itemBean) {
        AssetApi.RequestTokenIdAsset(itemBean.getTokenId(),new SimpleResponseListener<AssetDataResponse>(){
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(AssetDataResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    List<AssetDataResponse.ArrayBean> data = response.getArray();
                    if (data != null) {
                        if (data.size()>0) {
                            AssetDataResponse.ArrayBean assetBean = data.get(0);
                            if (assetBean != null) {
                                getUI().updateAssettByToken(itemBean,assetBean.getFree());
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        } );
    }
}
